import {
  api,
  util,
  storage
} from '../../../js/util.js' 
import {
  router
} from '../../../js/router.js'
import {
  config
} from "../../../js/modules/gloab";
import {
  pagesInfo
} from '../../../js/router'; 
var app = getApp();
const pageBehavior = require('../../../js/common/PageBehavior')

Page({
  behaviors: [pageBehavior],
  /**
   * 页面的初始数据 
   */
  data: {
    thirdPath: "",
    thirdDomain: api.h5Domain,
    isHidden: false,
    timer: null,
    enableJoin: true,
    isParsed: false,
    loopCount: 0 //循环数量
  },
  getParam(options) {
    let p = {
      action: options.action,
      hashPath: options.hashPath||"",
      params: {
        appid:api.appId,
        secret:api.secret
      }
    }
    for (let key in options) {
      if (key != "action" && key != "hashPath" && key != "__proto__") {
        p.params[key] = options[key];
      }
    }
    return p;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // wx.hideShareMenu();
    //获得参数
    this.data.params = this.getParam(options);
    //action=skip时，是登录或支付后跳转回来的页面
    if (options.action == "skip") {
      this.parseComplete();
    } else {
      //如果域名没解析完，递规等待
      if (app.dns.fkId == 0) {
        this.check_dns_analysis();
      } else {
        this.parseComplete();
      }

    }

  },
  getThirdPath(){
    let thirdDomain = this.data.thirdDomain;
    //如果是通用下，则将url赋值给h5  
    if (app.dns.proprietorId != app.dns.fkId) {
      let dir = (storage.get("LoginSessionVirtualDirKey") || "");
      thirdDomain = this.data.thirdDomain + (dir.length > 0 ? "/" + dir : "");
    }
    return thirdDomain;
  },
  parseComplete(){
    let thirdDomain=this.getThirdPath();
    //如果运营主体为0，则直接跳转到登录页面
    if (app.dns.proprietorId == 0) {
      router.redirect({
        path: "pages/account/login/login",
        params:{
          logout:true
        }
      });
    }
    else {
      let p=this.data.params;
      let path = router.joinParams({
        params: p.params,
        path: thirdDomain + (p.hashPath || "")
      });
      this.setData({
        isParsed:true,
        thirdPath: path
      }, () => {
        console.log(this.data.thirdPath);
      });
    }
  },
  /**
   * 检测dns和分析
   */
  check_dns_analysis: function() {
    let that = this;
    this.data.timer = setInterval(() => {
      if (app.dns.fkId > 0) {
        clearInterval(that.data.timer);
        this.parseComplete();
      }
      if (that.data.loopCount > 60) {
        clearInterval(that.data.timer);
        that.data.loopCount = 0;
      }
    }, 100);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setNavigationBarTitle({
      title: api.title
    });
    api.titleColor = api.titleColor;
    wx.setNavigationBarColor({
      backgroundColor: api.titleColor,
      frontColor: '#ffffff',
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  handleMessage: function(message) {
    console.log('handleMessage', message)
    const {
      action,
      data
    } = message;
    console.log(action,'h5======share',data);
    let imageUrl = ''
    if (action === 'postData') {
      if (this.eventChannel) {
        this.eventChannel.emit('receiveData', data);
      }
    }
    if (action === 'detail') {
      var that = this;
      let {
        id,
        discountId,
        discountType,
        productName,
        ikcqr
      } = data;
      imageUrl = data.imageUrl //自定义分享图片
      let path = "packageStore/pages/product/detail/detail" + `?id=${id}&ptype=0&productId=${id}&discountId=${discountId}&discounttype=${discountType}&scene=${ikcqr}`;
      let shareData = {
        title: productName,
        path: path,
      }
      that.setData({
        ...shareData
      })
    }
    else if (action =="register"){
      let path ="pages/account/register/register?role=store";
      this.setData({
        title: "零售商注册分享",
        path: path
      })
    }
    else if(action=="distribution"){     
      let path = pagesInfo.distributionInvite.url+"?scene="+data.scene;
      this.setData({
        title: "邀请加入",
        path: path
      })
    }else if(action == 'backLogin'){
      router.redirect({
        path: "pages/account/login/login",
        params:{
          logout:true
        }
      });
    }else if(action == 'share'){
      let oddNumber = data.oddNumber || '';
      let url = data.url || '';
      if (oddNumber==''&&url!='') {
        oddNumber = url.substring(url.lastIndexOf('/')+1, url.indexOf('?')>-1?url.lastIndexOf('?'):url.length);
      }
      let path ="packageStore/pages/purchase/detail/detail?view=1&oddNumber="+oddNumber;
      this.setData({
        title: "订单分享",
        path: path
      });
    }else if(action == 'promotion'){
      let id = data.id || '';
      let url = data.url || '';
      if (id==''&&url!='') {
        id = url.substring(url.lastIndexOf('/')+1, url.indexOf('?')>-1?url.lastIndexOf('?'):url.length);
      }
      let obj = util.urlParse(url);
      let path ="packageStore/pages/market/promotions/detail?id="+id+"&ikcqr="+obj.ikcqr;
      this.setData({
        title: "活动分享",
        path: path
      })
    }else{
      router.redirect({
        path: "pages/account/login/login?role=store",
        params:{}
      });
    }
    this.setData({
      imageUrl
    })
  },
  onH5PostMessageEvent(e) {
    // alert(e.detail,'---detail');
    const {
      data
    } = e.detail;
    if (Array.isArray(data)) {
      const messages = data.map(item => {
        try {
          const object = JSON.parse(item);
          this.handleMessage(object);
          return object;
        } catch (error) {
          return item;
        }
      });
      this.setData({
        messages: [...messages],
      });
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("onUnload");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let {
      title,
      path,
      imageUrl
    } = this.data;
    console.log(title, path, imageUrl)
    if (!path) {
      path = `pages/index`
    }
    // todo: 图片调为5:4
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  }
})